<script>
	import dictAPi from '@/api/dict.js';
	import initApp from '@/common/appInit.js';
	import openApp from '@/common/openApp.js';
	import mqttApi from '@/api/my-mqtt.js';
	// #ifdef H5
		openApp() //创建在h5端全局悬浮引导用户下载app的功能
	// #endif
	import checkIsAgree from '@/pages/uni-agree/utils/uni-agree.js';
	import uniIdPageInit from '@/uni_modules/uni-id-pages/init.js';
	// #ifdef APP
	import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update';
	import callCheckVersion from '@/uni_modules/uni-upgrade-center-app/utils/call-check-version';
	// #endif
	export default {
		globalData: {
			searchText: '',
			appVersion: {},
			config: {},
			$i18n: {},
			$t: {},
			mqttReconnectTimer: null,  // MQTT重连定时器
			mqttCheckTimer: null,      // MQTT检查防抖定时器
			lastCheckTime: 0           // 上次检查时间戳
		},
		onLaunch: function() {
			console.log('App Launch')
			this.globalData.$i18n = this.$i18n
			this.globalData.$t = str => this.$t(str)
			initApp();
			uniIdPageInit()
			this.getCommonDict()
			
			// 监听语言切换事件,重新加载字典数据
			uni.$on('changeLanguage', () => {
				console.log('[APP] 监听到语言切换,重新加载字典数据')
				this.getCommonDict()
			})
			
			// 初始化全局MQTT连接
			this.initGlobalMqtt();
			
			// 监听来自页面的MQTT重连请求
			uni.$on('check-mqtt-connection', () => {
				console.log('[APP] 收到MQTT连接检查请求')
				this.checkAndReconnectMqtt()
			})
			
			// #ifdef APP
			// 应用启动时自动检查更新(静默检查)
			this.checkAppUpdate();
			//checkIsAgree(); APP端暂时先用原生默认生成的。目前,自定义方式启动vue界面时,原生层已经请求了部分权限这并不符合国家的法规
			// #endif

			// #ifdef H5
			// checkIsAgree(); // 默认不开启。目前全球,仅欧盟国家有网页端同意隐私权限的需要。如果需要可以自己去掉注视后生效
			// #endif

			// #ifdef APP-PLUS
			//idfa有需要的用户在应用首次启动时自己获取存储到storage中
			/*var idfa = '';
			var manager = plus.ios.invoke('ASIdentifierManager', 'sharedManager');
			if(plus.ios.invoke(manager, 'isAdvertisingTrackingEnabled')){
				var identifier = plus.ios.invoke(manager, 'advertisingIdentifier');
				idfa = plus.ios.invoke(identifier, 'UUIDString');
				plus.ios.deleteObject(identifier);
			}
			plus.ios.deleteObject(manager);
			console.log('idfa = '+idfa);*/
			// #endif
		},
		onShow: function() {
			console.log('App Show - 应用回到前台')
			
			// 清除重连定时器
			if (this.globalData.mqttReconnectTimer) {
				clearTimeout(this.globalData.mqttReconnectTimer)
				this.globalData.mqttReconnectTimer = null
			}
			
			// 应用从后台恢复时，先断开MQTT再重新连接，确保连接状态正常
			// 延迟1秒等待应用完全恢复后再操作
			setTimeout(() => {
				this.forceReconnectMqtt()
			}, 1000)
			
			// #ifdef APP
			// 应用从后台恢复时检查更新(静默检查,避免频繁打扰用户)
			this.checkAppUpdate();
			// #endif
		},
		onHide: function() {
			console.log('App Hide - 应用进入后台')
			// 应用进入后台时不主动断开MQTT，让它保持连接
			// 如果系统回收了连接，会在onShow时自动重连
		},
		methods: {
			/**
			 * 检查应用更新(自动调用,静默检查)
			 */
			async checkAppUpdate() {
				// #ifdef APP
				try {
					console.log('[APP] 开始检查应用更新...')
					const res = await callCheckVersion();
					console.log('[APP] 更新检查结果:', res);
					
					if (res && res.result && res.result.code > 0) {
						// 有新版本,自动弹出更新提示
						console.log('[APP] 发现新版本,弹出更新提示')
						checkUpdate();
					} else {
						// 无更新或检查失败,静默处理
						console.log('[APP] 暂无更新或检查失败:', res?.result?.message || '未知')
					}
				} catch (error) {
					console.error('[APP] 检查更新失败:', error)
				}
				// #endif
			},
			getCommonDict() {
				// 将常用字典 缓存起来
				const currentLang = uni.getStorageSync('CURRENT_LANG') || 'zh-Hans';
				dictAPi.getAllDictDataMap().then(res => {
					if(res.errCode === 0) {
						let pattern_category = res.data.pattern_category;
						// 处理多语言标签，优先使用当前语言，如果没有则使用label
						if (pattern_category && Array.isArray(pattern_category)) {
							pattern_category = pattern_category.map(item => {
								let displayLabel = item.label;
								if (item.labels && typeof item.labels === 'object') {
									displayLabel = item.labels[currentLang] || item.labels['zh-Hans'] || item.label;
								}
								return {
									...item,
									label: displayLabel
								};
							});
						}
						uni.setStorageSync('pattern_category', pattern_category)
					}
				})
			},
			/**
			 * 初始化全局MQTT连接
			 */
			async initGlobalMqtt() {
				try {
					console.log('[APP] 初始化全局MQTT连接...')
					
					// 所有用户使用统一的MQTT认证信息
					// MQTT连接与应用用户账号无关，通过订阅不同设备主题区分用户
					await mqttApi.connect({
						username: 'linyuchi',
						password: 'adSd@@4d'
					})
					
					console.log('[APP] ✅ 全局MQTT连接成功')
					
					// 通知所有页面MQTT已连接，可以启动设备监听
					uni.$emit('mqtt-connected')
				} catch (error) {
					console.error('[APP] ❌ 全局MQTT连接失败:', error)
					// 失败后延迟5秒重试
					this.globalData.mqttReconnectTimer = setTimeout(() => {
						this.initGlobalMqtt()
					}, 5000)
				}
			},
			
			/**
			 * 检查并重连MQTT
			 */
			async checkAndReconnectMqtt() {
				try {
					// 防抖：如果距离上次检查不到5秒，忽略本次请求
					const now = Date.now()
					if (now - this.globalData.lastCheckTime < 5000) {
						console.log('[APP] 距离上次MQTT检查不到5秒，忽略本次请求')
						return
					}
					this.globalData.lastCheckTime = now
					
					console.log('[APP] 检查MQTT连接状态...')
					
					const isConnected = mqttApi.isConnected()
					console.log('[APP] MQTT连接状态:', isConnected)
					
					if (!isConnected) {
						console.log('[APP] MQTT未连接，准备重连...')
						await this.initGlobalMqtt()
					} else {
						console.log('[APP] MQTT已连接，无需重连')
					}
				} catch (error) {
					console.error('[APP] 检查MQTT连接失败:', error)
					// 检查失败也尝试重连
					this.globalData.mqttReconnectTimer = setTimeout(() => {
						this.initGlobalMqtt()
					}, 3000)
				}
			},
			
			/**
			 * 强制重连MQTT（先断开再连接）
			 */
			async forceReconnectMqtt() {
				try {
					console.log('[APP] 应用恢复，强制重连MQTT...')
					
					// 先断开现有连接
					try {
						console.log('[APP] 断开现有MQTT连接...')
						await mqttApi.disconnect()
						console.log('[APP] MQTT已断开')
					} catch (disconnectError) {
						console.warn('[APP] 断开MQTT时出错（可能已断开）:', disconnectError)
					}
					
					// 等待500ms确保断开完成
					await new Promise(resolve => setTimeout(resolve, 500))
					
					// 重新连接
					console.log('[APP] 重新建立MQTT连接...')
					await this.initGlobalMqtt()
					
					console.log('[APP] ✅ MQTT强制重连完成')
				} catch (error) {
					console.error('[APP] ❌ MQTT强制重连失败:', error)
					// 失败后延迟3秒重试
					this.globalData.mqttReconnectTimer = setTimeout(() => {
						this.forceReconnectMqtt()
					}, 3000)
				}
			}
		}
	}
</script>

<style lang="scss">
	* {
		box-sizing: border-box;
	}
	/*每个页面公共css */
	uni-app, uni-page, uni-page-wrapper, uni-page-body {
		height: 100%;
		width: 100%;
		overflow-x: hidden;
		position: relative;
	}
	
	/* 防止页面横向滚动 */
	page {
		width: 100%;
		height: 100%;
		overflow-x: hidden;
		overflow-y: auto;
	}
	
	/* 确保所有view元素不会超出屏幕 */
	view {
		max-width: 100%;
	}
	
	/* 隐藏滚动条但保持滚动功能 */
	::-webkit-scrollbar {
		width: 0;
		height: 0;
		display: none;
	}
	
	/* 确保所有容器不会超出视口 */
	.pad-20, .pad-0-20 {
		overflow-x: hidden;
	}
	
	.empty-box {
		width: 100%;
		height: 112rpx;
		margin: 84px auto 0;
		text-align: center;
		display: flex;
		justify-content: center;
		align-items: center;
		.empty-text {
			margin-top: 26rpx;
			color: rgba(0, 0, 0, 0.40);
		}
	}
	.empty-img {
		width: 112rpx;
		height: 112rpx;
		margin: 0 auto 0;
		display: block;
	}
	.common-bg {
		width: 100%;
		max-width: 100vw;
		background-image: url(/static/images/common-bg.png);
		background-size: 100% 100%;
		background-color: #fff;
		background-position: top;
		background-repeat: no-repeat;
		min-height: 800rpx;
		overflow-x: hidden;
	}
	.img-100 {
		width: 100%;
		height: 100%;
	}
	uni-image{
		width: 100% ;
		height: 100% ;
	}
	.pad-20 {
		padding: 40rpx;
		max-width: 100%;
		box-sizing: border-box;
	}
	.pad-0-20 {
		padding: 0 40rpx;
		max-width: 100%;
		box-sizing: border-box;
	}
	.font-11 {
		font-size: 22rpx;
	}
	.font-12 {
		font-size: 24rpx;
	}
	.font-14 {
		font-size: 28rpx;
	}
	.font-16 {
		font-size: 32rpx;
	}
	.font-18 {
		font-size: 36rpx;
	}
	.font-22 {
		font-size: 44rpx;
	}
	.font-20 {
		font-size: 40rpx;
	}
	.font-24 {
		font-size: 48rpx;
	}
	.font-500 {
		font-weight: 500;
	}
	.font-600 {
		font-weight: 600;
	}
	.col-000-8 {
		color: rgba(0, 0, 0, 0.8);
	}
	.col-000-4 {
		color: rgba(0, 0, 0, 0.4);
	}
	.col-f-4 {
		color: rgba(255, 255, 255, 0.4);
	}
	.col-fff {
		color: #fff;
	}
	.col-3C82F6 {
		color: #3C82F6;
	}
	.flex-center-center {
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.flex {
		display: flex;
	}
	.flex-center {
		align-items: center;
	}
	.flex-content-center {
		justify-content: center;
	}
	.flex-between {
		justify-content: space-between;
	}
	.bg-fff {
		background-color: #fff;
	}
	.m-t-4 {
		margin-top: 8rpx;
	}
	.m-t-8 {
		margin-top: 16rpx;
	}
	.m-t-20 {
		margin-top: 40rpx;
	}
	.m-t-24 {
		margin-top: 48rpx;
	}
	.m-t-40 {
		margin-top: 80rpx;
	}
	.w-100 {
		width: 100%;
	}
	.text-center {
		text-align: center;
	}
	.shadow {
		background: #FFFFFF;
		box-shadow: 0px 0px 8rpx 0px rgba(0,0,0,0.08);
		border-radius: 16rpx;
	}
</style>
